import {View, Text} from 'react-native';
import {UserToken} from '../../../../db/models/userTokenModel';
import {primaryColor2} from '../../../../theme/default';
import {useSolanaOwnerTokenAccountsProvider} from '../../../../hooks/useSolana/useSolanaOwnerTokenAccounts';
import {useTokenPriceProvider} from '../../../../hooks/useTokenPriceProvider';
import {useEffect, useState} from 'react';
import BigNumber from 'bignumber.js';
import {formatCurrency} from '../../../../utils';

type TotalAssetsProp = {
  userTokenList: UserToken[];
};

export function TotalAssets({userTokenList}: Readonly<TotalAssetsProp>) {
  const {accountsloading, userTokens} = useSolanaOwnerTokenAccountsProvider();
  const {priceLoading, tokenPrices} = useTokenPriceProvider();
  const [tokenTotalValue, setTokenTotalValue] = useState<number>();
  useEffect(() => {
    if (!priceLoading && !accountsloading) {
      console.log('tokenPrices', tokenPrices);
      let totalValue = BigNumber(0);
      for (let i = 0; i < userTokens.length; i++) {
        const tokenPrice = tokenPrices.find(item => {
          return (
            item.symbol.toLowerCase() == userTokens[i].symbol.toLowerCase()
          );
        });
        if (tokenPrice != undefined) {
          const tokenValue = BigNumber(userTokens[i].uiAmount!).multipliedBy(
            BigNumber(tokenPrice.price),
          );
          totalValue = totalValue.plus(tokenValue);
          setTokenTotalValue(totalValue.toNumber());
        }
      }
    }
  }, [accountsloading, priceLoading]);

  return (
    <View style={{alignItems: 'center', paddingTop: 32, paddingBottom: 24}}>
      <Text style={{color: primaryColor2, fontSize: 32, fontWeight: '600'}}>
        {formatCurrency(tokenTotalValue ?? 0, 'SGD', 2, 2)}
      </Text>
    </View>
  );
}
